package com.dongjiantong.app.controller.farmrecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.model.FarmRecordsHarmlesses;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.farmrecords.service.FarmRecordsHarmlessesService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.enums.AnimalTypeEnum;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 防疫中心无害化记录 (非集中处理)
 * @author Lee
 * @date 2018/1/9
 */
@Slf4j
@OpenBean
public class FarmRecordsHarmlessesController {
    @Reference(version = "1.0.0"/*,retries = 0,timeout = 5000*/)
    public FarmRecordsHarmlessesService farmRecordsHarmlessesService;
    @Reference(version = "1.0.3"/*,retries = 0,timeout = 5000*/)
    public AnimalTypeService animalTypeService;

    @Reference(version = "1.0.0"/*,retries = 0,timeout = 5000*/)
    private FarmRecordsFileService farmRecordsFileService;

    /**
     * (政府端)
     * 根据养殖场id,起止时间或者状态查询非集中无害化处理记录 (条件都可以为空,表示查询所有)
     * @param farmId  请求的养殖场id
     * @param fromDate 请求的查询开始时间
     * @param toDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @param breedSecondType 动物种类
     * @return  Response<PageInfo<FarmRecordsHarmlesses>>
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsHarmlessesNoCenter.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","toDate","pageNum","pageSize","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsHarmlesses>> selectByFarmIdAndDate(
            @RequestParam(required = false) Long farmId,
            @RequestParam(required = false) String fromDate,
            @RequestParam(required = false) String toDate,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) Integer breedSecondType){
        if (farmRecordsHarmlessesService == null){
            throw new OPServerException("请检查 farmRecordsHarmlessesService 服务");
        }

        Map<String,Object> map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }

        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());

        map.put("animal_second_non_bull", AnimalTypeEnum.BULL.getCode());

        if (breedSecondType != null){
            map.put("breed_second_type",breedSecondType);
        }

        PageInfo<FarmRecordsHarmlesses> farmRecordsHarmlessesNoCenterPageInfo = farmRecordsHarmlessesService.selectByMap(pageNum,pageSize,map);
        return Response.ok(farmRecordsHarmlessesNoCenterPageInfo);
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsHarmlessesNoCenter.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsHarmlesses>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                        @RequestParam(required = false) Integer status,
                                                                        @RequestParam(required = false) Integer pageSize,
                                                                        @RequestParam(required = false) Integer pageNum){
        if (farmRecordsHarmlessesService == null){
            throw new OPServerException("farmRecordsHarmlessesService 服务为空,请重启服务后重试");
        }
        if (farmId == null){
            throw new OPServerException("养殖场id不能为空,请检查后重试");
        }

        if (pageSize == null){
            pageSize = 20;
        }
        if (pageNum == null){
            pageNum = 1;
        }

        //这里查询除牛之外的其他动物
        Integer nonBull = AnimalTypeEnum.BULL.getCode();

        PageInfo<FarmRecordsHarmlesses> farmRecordsHarmlessesNoCenterPageInfo = farmRecordsHarmlessesService.selectListByStatus(pageNum,pageSize,status,farmId,nonBull);

        return Response.ok(farmRecordsHarmlessesNoCenterPageInfo);
    }

    /**
     * 根据主键id查询对应非集中无害化处理记录
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsHarmlessesNoCenter.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsHarmlesses> selectById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求的id不能为空");
        }
        try {
            if (farmRecordsHarmlessesService == null){
                throw new OPServerException("farmRecordsHarmlessesService 为null,请检查");
            }
            FarmRecordsHarmlesses farmRecordsHarmlesses = farmRecordsHarmlessesService.selectByPrimaryKey(id);

            List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileService.selectPicOrVideoListByRelevanceIds(Lists.newArrayList(farmRecordsHarmlesses.getId()), FarmRecordsFileEnum.HARMLESSESNOCENTER.getCode(),Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode()));

            farmRecordsHarmlesses = farmRecordsHarmlessesService.setPicOrVideoByObject(farmRecordsHarmlesses,farmRecordsFileList);

            return Response.ok(farmRecordsHarmlesses);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * (非集中处理)
     * 新增一条非集中无害化记录 (暂存状态)
     * @param farmRecordsHarmlesses
     * @param toStatus 单据改变为状态
     * @return long 返回插入数据的id
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsHarmlessesNoCenter.createOne",
            paramNames = {"farmRecordsHarmlesses","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> createOne(@RequestBody(required = false) FarmRecordsHarmlesses farmRecordsHarmlesses,
                                                  @RequestParam(required = false) Integer toStatus){
        if (farmRecordsHarmlesses == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }
        if (farmRecordsHarmlessesService == null){
            throw new OPServerException("farmRecordsHarmlessesService 为null,请检查");
        }

        LoginInfo loginInfo = UserUtil.getCurrentUser();
        Integer isFrom = farmRecordsHarmlesses.getIs_from();

        Map<String,Object> result = farmRecordsHarmlessesService.createOne(loginInfo,farmRecordsHarmlesses, toStatus,isFrom);

        return Response.ok(result);
    }

    /**
     * 根据id或者number 更新一条单据信息
     * @param farmRecordsHarmlesses 请求的对象
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsHarmlessesNoCenter.updateByIdOrNumber",
            paramNames = {"farmRecordsHarmlesses","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Object> updateByIdOrNumber(@RequestBody (required = false) FarmRecordsHarmlesses farmRecordsHarmlesses,
                                               @RequestParam(required = false) Integer toStatus){
        if (farmRecordsHarmlesses == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }else{
            if (farmRecordsHarmlessesService == null){
                throw new OPServerException("farmRecordsHarmlessesService 为null,请检查");
            }
            if (farmRecordsHarmlesses.getId() == null){
                throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST,HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
            }
            Integer con = farmRecordsHarmlessesService.updateByIdOrNumber(farmRecordsHarmlesses,toStatus);

            Map<String,Object> map = Maps.newHashMap();
            if (con == 1) {
                map.put("updateResult","true");
            }else {
                map.put("updateResult","false");
            }

            return Response.ok(map);
        }
    }
}
